package com.hihonor.swing;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.SystemPropsUtil;
import cn.hutool.log.Log;
import com.hihonor.Main;
import com.hihonor.db.DsUtil;
import com.hihonor.db.JdbcTest;
import com.hihonor.model.DbSetting;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 李志雄
 * @since 2023-10-14
 */
public class SettingDialog extends JDialog {
    private static final Log log = Log.get();

    private final JTextField addressText = new JTextField("", 40);

    private final JTextField userText = new JTextField("", 40);

    private final JTextField passwordText = new JTextField("", 40);

    public SettingDialog(Main main) {
        this.setTitle("设置");
        this.setSize(new Dimension(500, 200));

        // 设置居中显示
        this.setLocationRelativeTo(null);

        // 设置成模态,父级容器不允许点击
        this.setModal(true);
        this.setLayout(new GridLayout(4, 1));
        this.setItems(main);
        this.setVisible(true);
    }

    private JLabel getLabel(String text) {
        JLabel label = new JLabel(text);
        label.setPreferredSize(new Dimension(80, 40));
        return label;
    }

    private void setItems(Main main) {
        // 从当前数据源获取连接地址
        DbSetting setting = DsUtil.getSetting();

        JPanel p1 = new JPanel();
        p1.setLayout(new FlowLayout(FlowLayout.LEFT));
        JLabel addressLab = getLabel("连接地址：");
        p1.add(addressLab);

        JTextField jdbcUrlText = getAddressText();
        jdbcUrlText.setText(setting.getUrl());
        p1.add(jdbcUrlText);
        this.add(p1);

        JPanel p2 = new JPanel();
        p2.setLayout(new FlowLayout(FlowLayout.LEFT));
        JLabel userLab = getLabel("用户名：");
        p2.add(userLab);

        JTextField dbUserText = getUserText();
        dbUserText.setText(setting.getUserName());
        p2.add(dbUserText);
        this.add(p2);

        JPanel p3 = new JPanel();
        p3.setLayout(new FlowLayout(FlowLayout.LEFT));
        JLabel passwordLab = getLabel("密码：");
        p3.add(passwordLab);

        JTextField dbPasswordText = getPasswordText();
        dbPasswordText.setText(setting.getPassword());
        p3.add(dbPasswordText);
        this.add(p3);

        JPanel p4 = new JPanel();
        p4.setLayout(new FlowLayout(FlowLayout.CENTER));
        JButton testBtn = new JButton("测试连接");
        testBtn.addActionListener(e -> {
            DbSetting dbSetting = getSetting(main);
            if (dbSetting != null) {
                JdbcTest.testConnect(main, dbSetting.getUrl(), dbSetting.getUserName(), dbSetting.getPassword());
            }
        });
        p4.add(testBtn);

        JButton saveBtn = new JButton("保存");
        p4.add(saveBtn);
        saveBtn.addActionListener(e -> {
            DbSetting dbSetting = getSetting(main);
            if (dbSetting != null) {
                boolean flag = JdbcTest.testConnect(main, dbSetting.getUrl(), dbSetting.getUserName(), dbSetting.getPassword());
                if (flag) {
                    String jarPath = SystemPropsUtil.get("user.dir");
                    File file = FileUtil.file(jarPath, "db.setting");
                    if (!file.exists()) {
                        try {
                            file.createNewFile();
                        } catch (Exception exception) {
                            log.error(exception.getMessage());
                        }
                    }
                    List<String> dbContentList = new ArrayList<>();
                    dbContentList.add("url = " + dbSetting.getUrl());
                    dbContentList.add("user = " + dbSetting.getUserName());
                    dbContentList.add("pass = " + dbSetting.getPassword());
                    dbContentList.add("showSql = false");

                    FileWriter fileWriter = new FileWriter(file);
                    fileWriter.writeLines(dbContentList);

                    log.info("save db file");
                    DsUtil.userNewDataSource(main, dbSetting, file.getPath());
                    this.setVisible(false);
                }
            }
        });
        this.add(p4);
    }

    private DbSetting getSetting(Main main) {
        String url = getAddressText().getText();
        String userName = getUserText().getText();
        String password = getPasswordText().getText();
        if (CharSequenceUtil.isBlank(url)) {
            main.showFailMsg("连接地址不能为空");
            return null;
        }
        if (CharSequenceUtil.isBlank(userName)) {
            main.showFailMsg("用户名不能为空");
            return null;
        }
        if (CharSequenceUtil.isBlank(password)) {
            main.showFailMsg("密码不能为空");
            return null;
        }
        DbSetting dbSetting = new DbSetting();
        dbSetting.setUrl(url);
        dbSetting.setUserName(userName);
        dbSetting.setPassword(password);
        return dbSetting;
    }

    public JTextField getAddressText() {
        return addressText;
    }

    public JTextField getUserText() {
        return userText;
    }


    public JTextField getPasswordText() {
        return passwordText;
    }
}